import Taro, { Component } from '@tarojs/taro'
import { View, ScrollView, Image, Text } from '@tarojs/components'
import './style.scss'

export default class Log extends Component {

  config = {
    navigationBarTitleText: '分类'
  }

  constructor(props) {
    super(props);
    this.state = {
      navTab: ['推荐', '圆桌', '热门', '收藏'],
      currentIndex: 0,
      date: '',
      stories: [],
      loading:true
    }
  }

  componentWillMount() {
  }

  componentDidMount() {
    this.getData();
  }

  componentWillUnmount() {
  }

  componentDidShow() {
  }

  componentDidHide() {
  }

  handleClick(index) {
    this.setState({
      currentIndex: index
    })
  }

  onToupper = () => {
    this.getData();
  };

  getData() {
    Taro.showLoading({ title: '加载中' });
    Taro.request({
      url: 'https://news-at.zhihu.com/api/4/news/latest',
      header: {
        'content-type': 'application/json'
      }
    }).then(res => {
      Taro.hideLoading();
      const { date, stories } = res.data;
      this.setState({
        date,
        stories,
        loading: false
      })
    }).catch(err => {
      console.log(err);
    })
  }

  render() {
    const {navTab, currentIndex, date, stories, loading} = this.state;
    return (
      <View>
        <View className='title'>
          {navTab.map((d, i) =>
            <View className={currentIndex === i ? 'flex-item active' : 'flex-item'} key={i} onClick={this.handleClick.bind(this, i)}>
              {d}
            </View>
          )}
        </View>
        <View className='content'>
          <View className='recommend' hidden={currentIndex !== 0}>
            <ScrollView
              scrollY
              scrollWithAnimation
              // style='height: 1500px'
              lowerThreshold='20'
              upperThreshold='20'
              onScrolltoupper={this.onToupper}
            >
              {
                loading ? <View>加载中</View> : stories.map((d, i) => {
                  return <View className='item-list' key={i}>
                    <View className='item-img'>
                      <Image className='item-list-img' src={d.images[0]} backgroundSize='cover' />
                    </View>
                    <View className='item-text'>
                      {d.title}
                      <Text>{date}</Text>
                    </View>
                  </View>
                })
              }
            </ScrollView>
          </View>
          <View className='round' hidden={currentIndex !== 1}>
            2
          </View>
          <View className='hot' hidden={currentIndex !== 2}>
            3
          </View>
          <View className='collect' hidden={currentIndex !== 3}>
            4
          </View>
        </View>
      </View>
    )
  }
}

